package com.wxj.bank.module.utils;

import com.wxj.bank.module.constant.Constants;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author shengtao
 * @Description: Base64工具类
 * @date 2019/01/30 10:51
 */
public class Base64Utils {

    private static final Logger LOGGER = LoggerFactory.getLogger(Base64Utils.class);

    //data:image/jpeg;base64,
    static final String IMAGEJPEGPREFIX="data:image/";
    static final String IMAGEBASE="base64";


    private Base64Utils(){}

    /**
     * 图片编码
     */
    public static String encode(byte[] textByte){
        try{
            String content = Base64.encodeBase64String(textByte);
            int prefix = content.indexOf(Constants.SYMBOL_MATH_PLUS);
            String pre = "";
            if(prefix >= 0){
                pre = content.substring(0,prefix);
                content = content.substring(prefix+1);
            }
            return IMAGEJPEGPREFIX+pre+Constants.SYMBOL_END+IMAGEBASE+Constants.SYMBOL_COMMA+content;
        }catch (Exception e){
            LOGGER.error("image encode error:{}",e.toString());
            return null;
        }
    }

    /**
     * 解码
     */
    public static byte[] decode(String text){
        if(StringUtils.isNotBlank(text)){
            int base64 = text.indexOf(IMAGEBASE);
            int prefix64 = text.indexOf(IMAGEJPEGPREFIX);
            if(base64 >= 0 && prefix64 >= 0){
                String suffex = text.substring(prefix64 + IMAGEJPEGPREFIX.length(),base64-1);
                if(StringUtils.isNotBlank(suffex)){
                    text = text.substring(text.indexOf(IMAGEBASE)+IMAGEBASE.length()+1);
                }
                text = suffex+Constants.SYMBOL_MID_LINE+text;
                return Base64.decodeBase64(text);
            }
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(System.getProperty("java.library.path"));

    }

}
